package com.lalosoft.twitter.helper;

import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.util.Log;

/** Helper class to add support for location in the status updates. */
public class LocationHelper {
	
	  static final String TAG = "LocationHelper";
	  static final String LOC = "@loc"; // code that gets replaced with location
	  Context context;
	  LocationManager locationManager;
	  Location location;
	  Criteria criteria;
	  String bestProvider;
	
	  public LocationHelper(Context context) {
	    this.context = context;
	    locationManager = (LocationManager) context
	        .getSystemService(Context.LOCATION_SERVICE);
	    criteria = new Criteria();
	    bestProvider = locationManager.getBestProvider(criteria, false);
	    location = locationManager.getLastKnownLocation(bestProvider);
	    Log.d(TAG, "construct'd with location: " + location);
	  }
	
	  /** Converts the LOC code to current location */
	  public String updateStatusForLocation(String input) {
	    String output;
	    if (location == null) {
	      output = input.replaceAll(LOC, "UNKNOWN");
	    } else {
	      output = input.replaceAll(LOC, String.format("(%f,%f)", 
	                location.getLongitude(), location.getLatitude()));
	    }
	    
	    // Make sure we don't go over 140 characters
	    output = (output.length() > 139) ? output.substring(0, 139) : output;
	    
	    Log.d(TAG, String.format("updateStatusForLocation(%s)=>%s", input, output));
	    return output;
	  }
}
